package com.qidianit.mes.pro.service.impl;

import com.qidianit.mes.common.Result;
import com.qidianit.mes.pojo.pro.AutoCode;
import com.qidianit.mes.pro.mapper.AutoCodeMapper;
import com.qidianit.mes.pro.service.AutoCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 自动编码服务实现类
 */
@Service
public class AutoCodeServiceImpl implements AutoCodeService {
    
    @Autowired
    private AutoCodeMapper autoCodeMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result generateCode(String prefix) {
        // 获取当前日期
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        
        // 使用悲观锁查询配置
        AutoCode autoCode = autoCodeMapper.selectByPrefixForUpdate(prefix);
        
        if (autoCode == null) {
            // 如果配置不存在，创建新配置
            autoCode = new AutoCode();
            autoCode.setPrefix(prefix);
            autoCode.setCurrentDate(today);
            autoCode.setCurrentNumber("001");
            autoCode.setDeleteFlag(0);
            autoCodeMapper.insertAutoCode(autoCode);
            return Result.success(prefix + today + "001");
        }
        
        // 检查日期是否变化
        if (!today.equals(autoCode.getCurrentDate())) {
            // 日期变化，重置序号
            autoCode.setCurrentDate(today);
            autoCode.setCurrentNumber("001");
        } else {
            // 日期未变化，序号递增
            int currentNum = Integer.parseInt(autoCode.getCurrentNumber());
            currentNum++;
            autoCode.setCurrentNumber(String.format("%03d", currentNum));
        }
        
        // 更新配置
        autoCodeMapper.updateAutoCode(autoCode);


        // 返回生成的编码
        return Result.success(prefix + autoCode.getCurrentDate() + autoCode.getCurrentNumber());
    }
    

}
